package classpath

import (
	"archive/zip"
	"errors"
	"io"
	"path/filepath"
)

// ZipEntry 表示zip或jar文件形式的类路径
type ZipEntry struct {
	absPath string
}

func newZipEntry(path string) *ZipEntry {
	//将path参数转化成绝对路径
	absPath, err := filepath.Abs(path)
	//出错则终止运行
	if err != nil {
		panic(err)
	}
	return &ZipEntry{absPath: absPath}
}

func (ze *ZipEntry) String() string {
	return ze.absPath
}

func (ze *ZipEntry) readClass(className string) ([]byte, Entry, error) {
	//读取封包
	r, err := zip.OpenReader(ze.absPath)
	if err != nil {
		return nil, nil, err
	}
	defer r.Close()

	//找到指定类文件
	for _, f := range r.File {
		if f.Name == className {
			rc, err := f.Open()
			if err != nil {
				return nil, nil, err
			}
			defer rc.Close()

			//返回二进制数据
			data, err := io.ReadAll(rc)
			if err != nil {
				return nil, nil, err
			}
			return data, ze, nil
		}
	}
	//类文件未找到，抛出错误
	return nil, nil, errors.New("class Not Found：" + className)
}
